import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const search = searchParams.get('search') || ''
    const status = searchParams.get('status') || 'all'
    const category = searchParams.get('category') || 'all'

    const where: any = {}
    
    if (search) {
      where.OR = [
        { name: { contains: search, mode: 'insensitive' } },
        { code: { contains: search, mode: 'insensitive' } },
        { description: { contains: search, mode: 'insensitive' } }
      ]
    }
    
    if (status !== 'all') {
      where.status = status
    }
    
    if (category !== 'all') {
      where.category = category
    }

    const products = await db.product.findMany({
      where,
      include: {
        creator: {
          select: { id: true, name: true, email: true }
        },
        versions: {
          orderBy: { createdAt: 'desc' },
          take: 1
        },
        _count: {
          select: { versions: true, histories: true }
        }
      },
      orderBy: { updatedAt: 'desc' }
    })

    return NextResponse.json(products)
  } catch (error) {
    console.error('Error fetching products:', error)
    return NextResponse.json(
      { error: 'Failed to fetch products' },
      { status: 500 }
    )
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { name, description, code, category, createdBy } = body

    if (!name || !createdBy) {
      return NextResponse.json(
        { error: 'Name and createdBy are required' },
        { status: 400 }
      )
    }

    // 检查用户是否存在，如果不存在则创建
    let user = await db.user.findUnique({
      where: { email: createdBy }
    })

    if (!user) {
      user = await db.user.create({
        data: {
          email: createdBy,
          name: createdBy.split('@')[0] // 使用邮箱前缀作为名称
        }
      })
    }

    // 检查产品编码是否已存在
    if (code) {
      const existingProduct = await db.product.findUnique({
        where: { code }
      })
      
      if (existingProduct) {
        return NextResponse.json(
          { error: 'Product code already exists' },
          { status: 400 }
        )
      }
    }

    const product = await db.product.create({
      data: {
        name,
        description,
        code,
        category,
        status: 'DRAFT',
        version: '1.0.0',
        createdBy: user.id
      },
      include: {
        creator: {
          select: { id: true, name: true, email: true }
        }
      }
    })

    // 创建产品历史记录
    await db.productHistory.create({
      data: {
        productId: product.id,
        action: 'CREATED',
        description: `产品 "${product.name}" 创建成功`,
        userId: user.id
      }
    })

    return NextResponse.json(product, { status: 201 })
  } catch (error) {
    console.error('Error creating product:', error)
    return NextResponse.json(
      { error: 'Failed to create product' },
      { status: 500 }
    )
  }
}